package com.zznzzn.myweb.service;

import com.zznzzn.myweb.exceptions.ServiceException;
import com.zznzzn.myweb.mapper.FileMapper;
import com.zznzzn.myweb.mapper.ItemMapper;
import com.zznzzn.myweb.pojo.File;
import com.zznzzn.myweb.pojo.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ItemServiceImpl implements ItemService{
    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private FileService fileService;

    @Override
    public int addItem(Item item) {
        if (itemMapper.insertItem(item)!=0){
            return 1;
        }else{
            throw new ServiceException("创建发布失败");
        }
    }

    @Override
    public List<Item> getItemByUser(String uuid,int level) {
        List<Item> items =itemMapper.queryItemByUser(uuid,level);
        if (items !=null){
            return items;
        }else{
            throw new ServiceException("发布不存在");
        }
    }

    @Override
    public Item getItemByItemid(String itemid) {
        Item items =itemMapper.queryItemBuItemId(itemid);
        if (items !=null){
            return items;
        }else{
            throw new ServiceException("发布不存在");
        }
    }

    @Override
    public int updateItem(Item item) {
        if (itemMapper.updateItem(item)!=0){
            return 1;
        }else{
            throw new ServiceException("修改发布失败");
        }
    }

    @Override
    public int deleteItem(String itemid) {
        Item item = getItemByItemid(itemid);
        List<File> files = item.getFiles();
        for (File file:files){
            fileMapper.deleteFile(file.getFileid());
            fileService.deleteLocalFile(file.getFilename(),false);
        }
        if (itemMapper.deleteItem(itemid)!=0){
            return 1;
        }else{
            throw new ServiceException("删除发布失败");
        }
    }

    @Override
    public int updateStatus(String itemid,int status) {
        if (itemMapper.updateStatus(status,itemid)!=0){
            return 1;
        }else{
            throw new ServiceException("更新失败");
        }
    }

    @Override
    public int updateWants(String itemid, int wants) {
        if (itemMapper.updateWants(wants,itemid)!=0){
            return 1;
        }else{
            throw new ServiceException("更新失败");
        }
    }

    @Override
    public List<Item> getAllItemByTime(int offset, int size,String uuid) {
        List<Item> items =itemMapper.queryAllItemByTime(offset,size,uuid);
        if (items !=null){
            return items;
        }else{
            throw new ServiceException("发布不存在");
        }
    }

    @Override
    public int itemCounts(String uuid, int status) {
        return itemMapper.itemCounts(uuid,status);
    }
}
